package com.ja.openchat.adapters;

import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.module.BaseLoadMoreModule;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.found.CircleDetailActivity;
import com.ja.openchat.views.UserAvatarView;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogReplyInfo;
import com.zy.openchat.core.model.circle.BlogUnreadInfo;
import com.zy.openchat.core.model.circle.BlogUserDateInfo;
import com.zy.openchat.core.model.photo.PhotoInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.ComplexSpannableStringUtils;
import com.zy.openchat.util.TimeUtils;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CircleMessageAdapter extends BaseQuickAdapter<BlogUnreadInfo, BaseViewHolder> implements LoadMoreModule {

    public CircleMessageAdapter() {
        super(R.layout.item_circle_reply);
        addChildClickViewIds(R.id.circleImageLayout);
    }

    public Map<Long, BlogInfo> blogInfoMap = new HashMap<>();

    public BlogInfo requestBlogInfo(long blogId) {
        if (blogId <= 0) {
            return null;
        }
        if (blogInfoMap.containsKey(blogId)) {
            return blogInfoMap.get(blogId);
        } else {
            TelegramManager.getTelegramManager().getBlogInfo(getContext(), blogId, new TgResultBlock<BlogInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, BlogInfo obj) {
                    updateBlogInfo(obj);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
            return null;
        }
    }

    public void updateBlogInfo(BlogInfo blogInfo) {
        if (blogInfo == null) {
            return;
        }
        blogInfoMap.put(blogInfo.id, blogInfo);
        for (int i = 0; i < getDefItemCount(); i++) {
            if (getItem(i) != null) {
                if (getItem(i).reply != null && getItem(i).reply.blog_id != null && getItem(i).reply.blog_id.blog_id == blogInfo.id) {
                    notifyItemChanged(i);
                } else if (getItem(i).id != null && getItem(i).id.blog_id == blogInfo.id) {
                    notifyItemChanged(i);
                }

            }
        }
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, BlogUnreadInfo blogUnreadInfo) {
        if ("blogMessageReply".equals(blogUnreadInfo.type)) {
            BlogReplyInfo blogReplyInfo = blogUnreadInfo.reply;
            UserInfo userInfo = UserInfo.getUserInfo(blogReplyInfo.user_id);
            UserAvatarView iv_icon = helper.getView(R.id.user_image);
            if (userInfo != null) {
                if (userInfo.profile_photo != null && !userInfo.profile_photo.isSmallPhotoDownloaded()) {
                    blogReplyInfo.isAvaterDownloaded = false;
                } else {
                    blogReplyInfo.isAvaterDownloaded = true;
                }
                helper.setText(R.id.user_name_text, userInfo.displayName());
                iv_icon.showUser(userInfo);
            } else {
                iv_icon.showDefault();
                helper.setText(R.id.user_name_text, "");
                blogReplyInfo.isAvaterDownloaded = false;
                TelegramManager.getTelegramManager().getUserSimpleInfo(blogReplyInfo.user_id);
            }
            helper.setText(R.id.post_time_text, TimeUtils.getMsgFormatTime(blogReplyInfo.date * 1000));
            if (blogReplyInfo.reply_user_id <= 0) {
                helper.setText(R.id.content_text, String.format(getContext().getString(R.string.commented_on_your_post), blogReplyInfo.text));
            } else {
                ComplexSpannableStringUtils.Builder builder = ComplexSpannableStringUtils.getBuilder(getContext().getString(R.string.replied_text));
                UserInfo replyUserInfo = UserInfo.getUserInfo(blogReplyInfo.reply_user_id);
                if (replyUserInfo != null) {
                    builder.append(String.format(" %s ", replyUserInfo.displayName())).setForegroundColor(getContext().getResources().getColor(R.color.login_btn_bg_color));
                } else {
                    builder.append("  ");
                    TelegramManager.getTelegramManager().getUserSimpleInfo(blogReplyInfo.reply_user_id);
                }
                builder.append(blogReplyInfo.text);
                helper.setText(R.id.content_text, builder.create());
            }
            onHandleBlogInfo(helper, blogReplyInfo.blog_id != null ? blogReplyInfo.blog_id.blog_id : 0, blogReplyInfo.blog_id != null);
        } else if ("blogMessageLiked".equals(blogUnreadInfo.type)) {
            BlogUserDateInfo dateInfo = blogUnreadInfo.user_date;
            if (dateInfo != null) {
                UserInfo userInfo = UserInfo.getUserInfo(dateInfo.user_id);
                UserAvatarView iv_icon = helper.getView(R.id.user_image);
                if (userInfo != null) {
                    if (userInfo.profile_photo != null && !userInfo.profile_photo.isSmallPhotoDownloaded()) {
                        blogUnreadInfo.isAvaterDownloaded = false;
                    } else {
                        blogUnreadInfo.isAvaterDownloaded = true;
                    }
                    helper.setText(R.id.user_name_text, userInfo.displayName());
                    iv_icon.showUser(userInfo);
                } else {
                    iv_icon.showDefault();
                    helper.setText(R.id.user_name_text, "");
                    blogUnreadInfo.isAvaterDownloaded = false;
                    TelegramManager.getTelegramManager().getUserSimpleInfo(dateInfo.user_id);
                }
                helper.setText(R.id.post_time_text, TimeUtils.getMsgFormatTime(dateInfo.date * 1000));
            }
            helper.setText(R.id.content_text, getContext().getString(R.string.liked_your_post));
            onHandleBlogInfo(helper, blogUnreadInfo.id != null ? blogUnreadInfo.id.blog_id : 0, blogUnreadInfo.id != null);

        } else if ("blogMessageBlog".equals(blogUnreadInfo.type)) {
            BlogInfo blogInfo = blogUnreadInfo.blog;
            if (blogInfo != null) {
                UserInfo userInfo = UserInfo.getUserInfo(blogInfo.user_id);
                UserAvatarView iv_icon = helper.getView(R.id.user_image);
                if (userInfo != null) {
                    if (userInfo.profile_photo != null && !userInfo.profile_photo.isSmallPhotoDownloaded()) {
                        blogUnreadInfo.isAvaterDownloaded = false;
                    } else {
                        blogUnreadInfo.isAvaterDownloaded = true;
                    }
                    helper.setText(R.id.user_name_text, userInfo.displayName());
                    iv_icon.showUser(userInfo);
                } else {
                    iv_icon.showDefault();
                    helper.setText(R.id.user_name_text, "");
                    blogUnreadInfo.isAvaterDownloaded = false;
                    TelegramManager.getTelegramManager().getUserSimpleInfo(blogInfo.user_id);
                }
                helper.setText(R.id.post_time_text, TimeUtils.getMsgFormatTime(blogInfo.date * 1000));
            }
            helper.setText(R.id.content_text, getContext().getString(R.string.post_mentioned_you));
            onHandleBlogInfo(helper, blogUnreadInfo.blog);
        }

    }


    private void onHandleBlogInfo(BaseViewHolder helper, long blogId, boolean isShow) {
        View circleImageLayout = helper.getView(R.id.circleImageLayout);
        if (isShow) {
            BlogInfo blogInfo = requestBlogInfo(blogId);
            onHandleBlogInfo(helper, blogInfo);
        } else {
            circleImageLayout.setVisibility(View.GONE);
        }
    }

    private void onHandleBlogInfo(BaseViewHolder helper, BlogInfo blogInfo) {
        View circleImageLayout = helper.getView(R.id.circleImageLayout);
        if (blogInfo != null) {
            List<Object> urls = blogInfo.getMedioInfos();
            if (Common.isEmpty(urls)) {
                circleImageLayout.setVisibility(View.GONE);
            } else {
                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CircleDetailActivity.startDetail(getContext(), blogInfo.id);
                    }
                });
                circleImageLayout.setVisibility(View.VISIBLE);
                blogInfo.checkMediaDownload(getContext());
                ImageView imageView = helper.getView(R.id.circleImage);
                Object o = urls.get(0);
                if (o instanceof PhotoInfo) {
                    PhotoInfo photoInfo = (PhotoInfo) o;
                    if (photoInfo.isPhotoDownloaded()) {
                        Glide.with(getContext())
                                .load(photoInfo.getPhotoImagePath())
                                .into(imageView);
                    } else {
                        imageView.setImageResource(R.drawable.image_chat_placeholder);
                    }
                } else if (o instanceof VideoInfo) {
                    VideoInfo videoInfo = (VideoInfo) o;
                    if (videoInfo.isVideoDownloaded()) {
                        Glide.with(getContext())
                                .load(videoInfo.localVideoPath())
                                .into(imageView);
                    } else {
                        imageView.setImageResource(R.drawable.image_chat_placeholder);
                    }
                } else {
                    imageView.setImageResource(R.drawable.image_chat_placeholder);
                }
            }
        } else {
            circleImageLayout.setVisibility(View.GONE);
        }
    }

    public int getRealItemCount() {
        return getDefItemCount();
    }

    @Override
    public @NotNull BaseLoadMoreModule addLoadMoreModule(@NotNull BaseQuickAdapter<?, ?> baseQuickAdapter) {
        return new BaseLoadMoreModule(baseQuickAdapter);
    }
}
